package com.dodock.android.banglapapers.ui;

import java.util.Vector;

import org.json.JSONArray;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dodock.android.banglapapers.BanglaNews;
import com.dodock.android.banglapapers.InternetConnectivity;
import com.dodock.android.banglapapers.MyApplication;
import com.dodock.android.banglapapers.Newspapers;
import com.dodock.android.banglapapers.R;
import com.dodock.android.banglapapers.WebServerOperation;
import com.dodock.android.banglapapers.imageLoader.ImageLoader;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.urbanairship.UAirship;
import com.urbanairship.push.PushManager;

public class HomeActivity extends BaseActivity {

	private ProgressDialog progressDialog;
	private boolean bError = false;
	public static Vector<Newspapers> newspapersList;
	
	private Tracker mGaTracker;
	private GoogleAnalytics mGaInstance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//Google Analytics
		try{
		    mGaInstance = GoogleAnalytics.getInstance(this);
		    mGaTracker = mGaInstance.getTracker(getResources().getString(R.string.ga_trackingId));
		}
		catch (Exception e) {
		}
		//--Google Analytics
		
		
		setContentView(R.layout.home);

		TextView titleView = (TextView) findViewById(R.id.title);
		titleView.setText(R.string.home);

		ImageButton settingsButton = (ImageButton) findViewById(R.id.settingsBtn);
		settingsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				settingsActivity();
			}
		});

		Button topNewsButton = (Button) findViewById(R.id.topNews);
		topNewsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(HomeActivity.this,
						TopNewsActivity.class);
				startActivity(intent);
			}
		});

		Button favouritButton = (Button) findViewById(R.id.favorite);
		favouritButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(HomeActivity.this,
						FavouritNewsActivity.class);
				startActivity(intent);
			}
		});

		Button savedNewsButton = (Button) findViewById(R.id.savedNews);
		savedNewsButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(HomeActivity.this,
						SavedNewsActivity.class);
				startActivity(intent);
			}
		});

		loadNewspapers();
	}

	private void loadNewspapers() {
		if (InternetConnectivity.isConnectedToInternet(this)) {
			progressDialog = ProgressDialog.show(this, null,
					"Loading. Please wait...", true, false);
			GetNewspapers gcit = new GetNewspapers();
			gcit.execute();
		} else {
			Toast toast = Toast.makeText(this,
					"Enable mobile network or Wi-Fi to download data",
					Toast.LENGTH_LONG);
			toast.show();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		com.facebook.Settings.publishInstallAsync(this, MyApplication.fb_app_id);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		try {
			mGaTracker.sendView("/Home");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
	}


	
	private class GetNewspapers extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			
			try {
				String device_id = Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID);
				if(device_id != null){ 
				       try {
				    	   String push_id = PushManager.shared().getAPID();
							WebServerOperation.HTTPrequest(String.format("http://api0.dodock.net/bpapi/android_ping.php?device_id=%s&push_id=%s&app_version=%s", 
									   device_id,
									   (push_id==null?"":push_id),
									   MyApplication.app_version));
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
			getNewsPapersListJson();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			try{
				progressDialog.dismiss();
				progressDialog = null;
				if (!bError){
					showContentView();
				}
			}
			catch (Exception e) {
			}
			
		}
	}

	private void getNewsPapersListJson() {
		String urlPath = BanglaNews.BASE_URL + "DDNGetNewspapers" + "?appVersion="+MyApplication.app_version;
		try {
			String serverResonse = WebServerOperation.HTTPrequest(urlPath);
			parseNewsPapersListJSON(serverResonse);
		} catch (Exception e) {
			Log.e("HomeActivity", "getNewsPapersListJson() : " + e.toString());
			bError = true;
		}
	}

	private void parseNewsPapersListJSON(String serverResonse) throws Exception {
		// TODO Auto-generated method stub
		JSONArray menuObject1 = new JSONArray(serverResonse);
		newspapersList = new Vector<Newspapers>();
		for (int j = 0; j < menuObject1.length(); j++) {
			Newspapers newspapers = new Newspapers();
			newspapers.setId(menuObject1.getJSONObject(j).getString("id"));
			newspapers.setName(menuObject1.getJSONObject(j).getString("name"));
			newspapers
					.setLanguage(menuObject1.getJSONObject(j).getString("ln"));
			newspapers.setLogo(menuObject1.getJSONObject(j).getString("logo"));
			newspapersList.add(newspapers);
		}
		bError = false;
	}

	private void showContentView() {
		// TODO Auto-generated method stub
		LinearLayout mainContainer = (LinearLayout) findViewById(R.id.homeMainContainer);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 70);
		params.setMargins(10, 15, 10, 0);
		LinearLayout.LayoutParams logoParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		for (int no = 0; no < newspapersList.size(); no++) {
			LinearLayout container = new LinearLayout(this);
			container.setLayoutParams(params);
			container.setBackgroundResource(R.drawable.round_rectangle_white);
			container.setGravity(Gravity.CENTER);
			ImageLoader imageLoader = new ImageLoader(this);
			ImageView logo = new ImageView(this);
			logo.setLayoutParams(logoParams);
			logo.setScaleType(ScaleType.FIT_XY);
			logo.setPadding(20, 8, 20, 8);
			imageLoader.DisplayImage(
					BanglaNews.BASE_URL + newspapersList.get(no).getLogo(),
					R.drawable.logo, logo, true, container);
			final int position = no;
			container.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(HomeActivity.this,
							NewsCategoryActivity.class);
					intent.putExtra("newsId", newspapersList
							.elementAt(position).getId());
					intent.putExtra("language",
							newspapersList.elementAt(position).getLanguage());
					intent.putExtra("paperName",
							newspapersList.elementAt(position).getName());
					startActivity(intent);
				}
			});
			container.addView(logo);
			mainContainer.addView(container);
		}
		
		LinearLayout btnContainer = new LinearLayout(this);
		btnContainer.setLayoutParams(params);
		btnContainer.setGravity(Gravity.CENTER);
		Button button = new Button(this);
		LinearLayout.LayoutParams buttonParms = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 70);
		button.setLayoutParams(buttonParms);
		button.setBackgroundResource(R.drawable.round_rectangle_white);
		button.setText(R.string.archive);
		button.setTextColor(getResources().getColor(R.color.textcolor));
		button.setTextAppearance(this, android.R.attr.textAppearanceLarge);
		button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
		button.setTypeface(Typeface.DEFAULT, Typeface.BOLD);

		button.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(HomeActivity.this,
						ArchiveActivity.class);
				startActivity(intent);
			}
		});
		btnContainer.addView(button);
		mainContainer.addView(btnContainer);
		
		
		
		checkConditionForNagscreen();
	}
	
	
	
	private void checkConditionForNagscreen(){
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		if (prefs.getBoolean("RATED", false) == false) {
			int count = prefs.getInt("COUNT", 0);
			Log.e("Nagscreen","not rated");
			if(prefs.getBoolean("CANCEL", false) == false){
				if (count == 4) {
					Log.e("Nagscreen","maybe later time 5 showing nagging dialog ");
					showNaggingDialog();
				} else {
					Log.e("Nagscreen","maybe later time less 5 counting and exit ");
					countNext(count);
				}
			}else{
				if (count == 20) {
					Log.e("Nagscreen","cancel and time 20 showing nagging dialog");
					showNaggingDialog();
				} else {
					Log.e("Nagscreen","cancel and time less 20 counting next and exit");
					countNext(count);
				}
			}			
		} else {
			Log.e("Nagscreen","rated");
			try{
				
				PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
				String version = pInfo.versionName;
				Log.e("version installed",""+version);
				if(!version.equals(prefs.getString("VERSION", "1"))){
					Log.e("Nagscreen","version is not same");
					Editor editor = PreferenceManager
							.getDefaultSharedPreferences(
									getApplicationContext()).edit();
					editor.putBoolean("RATED", false);
					editor.putInt("COUNT", 1);
					editor.putString("VERSION", version);
					editor.commit();
				}else{
					Log.e("Nagscreen","version same");
				}
			}catch(Exception ex){
				Log.e("exception", ex.toString());
			}			
		}
	}
	
	private void countNext(int count) {
		// TODO Auto-generated method stub
		Editor editor = PreferenceManager.getDefaultSharedPreferences(
				getApplicationContext()).edit();
		editor.putInt("COUNT", count + 1);
		editor.commit();
	}

	private void showNaggingDialog() {
		// TODO Auto-generated method stub
		dialog = new Dialog(HomeActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.nag_dialog);
		dialog.setCancelable(false);
		Button rateBtn = (Button) dialog
				.findViewById(R.id.rate_application);
		rateBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {				
				try {
					Editor editor = PreferenceManager
							.getDefaultSharedPreferences(
									getApplicationContext()).edit();
					editor.putBoolean("RATED", true);
					PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
					String version = pInfo.versionName;
					editor.putString("VERSION", version);
					editor.commit();
					Intent i = new Intent(Intent.ACTION_VIEW);
					i.setData(Uri.parse("market://details?id="
							+ getPackageName()));
					startActivity(i);
				} catch (Exception ex) {
					Log.e("RATE", ex.toString());
				}
				dialog.cancel();				
			}
		});
		Button laterBtn = (Button) dialog.findViewById(R.id.later);
		laterBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				Editor editor = PreferenceManager
						.getDefaultSharedPreferences(
								getApplicationContext()).edit();
				editor.putBoolean("RATED", false);
				editor.putBoolean("CANCEL", false);
				editor.putInt("COUNT", 0);
				editor.commit();
				dialog.cancel();
			}
		});
		Button cancelBtn = (Button) dialog.findViewById(R.id.cancle);
		cancelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Editor editor = PreferenceManager
						.getDefaultSharedPreferences(
								getApplicationContext()).edit();
				editor.putBoolean("RATED", false);
				editor.putBoolean("CANCEL", true);
				editor.putInt("COUNT", 0);
				editor.commit();
				dialog.cancel();
			}
		});
		dialog.show();	
	}
	
	private Dialog dialog;	
}